const fs = require('fs');
const path = require('path');
const jsonFilePath = path.join(__dirname, '../json/navigation.json');

// 读取 JSON 文件中的导航数据
const readJsonData = () => {
    const data = fs.readFileSync(jsonFilePath, 'utf8');
    return JSON.parse(data);
};

// 写入数据到 JSON 文件
const writeJsonData = (data) => {
    fs.writeFileSync(jsonFilePath, JSON.stringify(data, null, 2), 'utf8');
};

// 获取左侧导航栏数据
exports.getNavigation = (req, res) => {
    const navigationData = readJsonData();
    res.json({
        code: 0,
        message: '成功',
        content: navigationData
    });
};

// 添加导航项
exports.addNavigation = (req, res) => {
    const { title, link } = req.body;

    if (!title || !link) {
        return res.status(400).json({ code: 1, message: '标题和链接是必需的' });
    }

    let navigationData = readJsonData();
    const newNavItem = {
        id: navigationData.length ? navigationData[navigationData.length - 1].id + 1 : 1,
        title,
        link
    };

    navigationData.push(newNavItem);
    writeJsonData(navigationData);

    res.json({
        code: 0,
        message: '导航项添加成功',
        navigation: newNavItem
    });
};
